package org.groupg.filetodb.handler;

import com.google.common.base.Strings;
import com.lmax.disruptor.EventHandler;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.groupg.filetodb.model.ColumnConfig;
import org.groupg.filetodb.model.TableRunning;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class CSVReaderHandler implements EventHandler<TableRunning> {

    static final Logger logger = LoggerFactory.getLogger(CSVReaderHandler.class);
    private final File csvFile;
    private final int batchSize;

    public CSVReaderHandler(File csvFile, int batchSize) {
        this.csvFile = csvFile;
        this.batchSize = batchSize;
    }

    @Override
    public void onEvent(TableRunning event, long sequence, boolean endOfBatch) {
        List<ColumnConfig> columnConfigs = event.getColumnConfigs();
        String names = columnConfigs.stream().sorted(Comparator.comparing(ColumnConfig::getColumnIndex)).map(ColumnConfig::getColumnName).collect(Collectors.joining(","));
        String str = Strings.repeat("?,", columnConfigs.size());
        String sql = "insert into " + event.getTableConfig().getTableName() + " (" + names + ") values (" + str.substring(0, str.length() - 1) + ")";
        try {
            CSVParser parser = CSVParser.parse(getCsvFile(), event.getTableConfig().getCharset(), CSVFormat.Builder.create().setDelimiter(event.getTableConfig().getFieldSeparator()).setRecordSeparator(event.getTableConfig().getRecordSeparator()).build());
            parser.forEach(record -> {

            });
            parser.close();
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }

    }

    public int getBatchSize() {
        return batchSize;
    }


    public File getCsvFile() {
        return csvFile;
    }
}
